import numpy as np
import matplotlib.pyplot as plt
import subprocess
import matplotlib.cm as cm
import matplotlib.patches as mpatches
import scipy.io
def fixed_conf(input_mci,n,a,s,g,d):
    # 打开文件进行读取和写入
    with open(input_mci, 'r+') as file:
        lines = file.readlines()
        # 遍历每一行查找目标行并替换整行
        for i in range(len(lines)):
            if '# layer 1' in lines[i]:
                lines[i] = '{}  {}  {}  {}  {}# layer 1\n'.format(n,a,s,g,d)  # 替换为新的整行文本
        # 将文件指针移动到文件开头
        file.seek(0)
        # 清空文件内容
        file.truncate()
        # 将修改后的内容写回文件
        file.writelines(lines)
    
    
def run_simulation():
    command = r'C:\Users\Administrator\Desktop\TIO2\mcml.exe'
    args = ['C:\\Users\\Administrator\\Desktop\\TIO2\\my.mci']
    command_with_args = [command] + args
    subprocess.run(command_with_args)

def read_mco_and_write(mco_file):
    # 读取文本文件
    with open(mco_file, "r") as file:
        lines = file.readlines()
    # 寻找关键字"A_rz"所在的行
    s = 0
    start_line = 0
    shape = (0,0) # (dz, dr) 离散网格个数
    for i, line in enumerate(lines):
        if '# layer 1' in line:
            line_temp = line.split()
            n = float(line_temp[0])
            ua = float(line_temp[1])
            us = float(line_temp[2])
            g = float(line_temp[3])
        if 'No. of dz' in line:
            shape = (int(line.split()[0]),int(line.split()[1]))
        if "A_rz" in line :
            s = s+1
            if s ==2:
                start_line = i + 1  # 关键字所在行的下一行
                break
    # 读取关键字下面的数据直到遇到空行为止
    data_list = []
    for line in lines[start_line:]:
        line = line.strip()  # 去除行首和行尾的空白字符
        if line == "":
            break  # 遇到空行结束
        else:
            data_list.extend(line.split())
    # 将数据存储到一维NumPy数组中
    data_array = np.array(data_list, dtype=np.float32)
    data_2d = data_array.reshape(shape[1], shape[0])
    last_column = data_2d[:, -1]
    reversed_column = last_column[::-1][:-1]
    # print(last_column)
    # print(reversed_column)
    F_column = np.concatenate((reversed_column, last_column))
    linear_label = 'n={} ua={}cm-1 us={}cm-1 g={}'.format(n,ua,us,g)
    file = open('result.txt', 'a')
    file.write('{}\n'.format(linear_label))
    F_column.tofile(file, sep=' ')
    file.write('\n')
    file.close()
    # middle = len(F_column) // 2
    # x = np.arange(-middle, middle+1)
    # plt.plot(x, F_column,'o-',label=linear_label)
    # plt.xlabel('the nth dr')
    # plt.ylabel('photon density(cm-3)')
    # plt.title('down plate simulation')
    # plt.legend()
    # plt.show()
    # print(data_2d)
    # print(data_2d.shape)

# show data
def show():
    file_path = "result.txt"  
    # 读取文件并去除空行
    with open(file_path, "r") as file:
        lines = file.readlines()
        non_empty_lines = [line.strip() for line in lines if line.strip()]
    # 计算行数
    line_count = len(non_empty_lines)
    colors = cm.rainbow(np.linspace(0, 1, line_count//2))
    # 打印结果
    print("去除空行后的行数:", line_count)
    for i in range(0,line_count,2):
        linear_label = lines[i]
        F_column  = lines[i+1].replace("\n", "")
        F_column = np.fromstring(F_column, dtype=np.float64, sep=' ')
        middle = len(F_column) // 2
        x = np.arange(-middle, middle+1)
        plt.plot(x, F_column, 'o-', color=colors[i//2], label=linear_label)
    plt.xlabel('the nth dr')
    plt.ylabel('photon density(cm-3)')
    plt.title('Surface distribution of transmitted light')
    # 添加图例
    #num_per_row=5
    #plt.legend(ncol=num_per_row)
    #plt.legend()
    # 显示图形
    plt.show()

def save_mat():
    data = {}
    file_path = "result.txt"  
    # 读取文件并去除空行
    with open(file_path, "r") as file:
        lines = file.readlines()
        non_empty_lines = [line.strip() for line in lines if line.strip()]
    # 计算行数
    line_count = len(non_empty_lines)
    # 打印结果
    print("去除空行后的行数:", line_count)
    for i in range(0,line_count,2):
        data[lines[i].replace("\n", "").replace(".", "_").replace("cm-1", "").replace(" ", "").replace("=", "")] = lines[i+1].replace("\n", "")
        
    print(data)
    scipy.io.savemat('data.mat', data)
    

# # show2 data
# def show2():
#     file_path = "result.txt"  
#     # 读取文件并去除空行
#     with open(file_path, "r") as file:
#         lines = file.readlines()
#         non_empty_lines = [line.strip() for line in lines if line.strip()]
#     # 计算行数
#     line_count = len(non_empty_lines)
#     colors = cm.rainbow(np.linspace(0, 1, line_count//2))
#     # 打印结果
#     print("去除空行后的行数:", line_count)
#     label_list = []
#     fig2, ax2 = plt.subplots()
#     for i in range(0,line_count,2):
#         label_list.append(lines[i])
#         F_column  = lines[i+1].replace("\n", "")
#         F_column = np.fromstring(F_column, dtype=np.float64, sep=' ')
#         middle = len(F_column) // 2
#         x = np.arange(-middle, middle+1)
#         ax2.plot(x, F_column, 'o-', color=colors[i//2], label=lines[i]) 
#     ax2.set_xlabel('the nth dr')
#     ax2.set_ylabel('photon density(cm-3)')
#     ax2.set_title('Surface distribution of transmitted light')
#     fig1, ax1 = plt.subplots()
#     ax1.set_axis_off() 
#     for i in range(0,line_count,2):
#          # 关闭坐标轴
#         #ax1.text(0.1, 0.5, label_list, fontsize=10)
#         rect = mpatches.Rectangle((0, i * 0.5), 0.2, 0.2, facecolor=colors[i//2])
#         ax1.add_patch(rect)
#         ax1.text(0.3, i * 0.5 + 0.1, lines[i], fontsize=10, verticalalignment='center')

#     # 显示图形
#     plt.show()


if __name__ == '__main__': 
    experiment = 0
    n = 1.49
    g = 0.59
    d = 0.3
    ua = np.arange(0.07, 0.11, 0.01)
    us = np.arange(4/(1-g),14/(1-g), 1)
    us = np.round(us, decimals=1)
    if experiment:
        for i in range(len(ua)):
            for j in range(len(us)):
                fixed_conf('my.mci',n,ua[i],us[j],g,d)
                run_simulation()
                read_mco_and_write('my.mco')        
    else:
        save_mat()
        show()
            